<?php
/**
 * @filesource modules/article/controllers/IndexController.php
 * @author Tran Van Hoang
 * @abstract : List of actions in order
 *   - new
 *   - view
 *   - edit
 *   - delete
 *   - search
 *   - bulk
 *   - translate
 *   
 */ 
class Article_MasterController extends Clu_Controller_Action_Master
{
	public $m; //model

	public function init()
	{
		$this->m = new article_Model_Service();
		parent::init();
	}
	
	public function newAction() 
    {
//    	die();
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'create article') === false)
	    {
    	 	$this->renderError(null,t(68));
            return;
	    }
        $this->viewParams['form'] = new Form_Article();
//        $this->viewParams['form']->cluBuild(array('action' => 'new','view' => $this->view));
        
        $actionUrl = $this->view->hvnUrl(array('module' => 'article', 'action'=>'new'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'new', 'action_url' => $actionUrl, 
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        
        if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST)) 
        {
            $this->m->insertRaw($this->_request->getParams(), false);
            $lastInsertId = $this->db->lastInsertId();
            //forward to avoid refreshing
            $this->_forward("success", 'index' , 'article', array('lastInsertId' => $lastInsertId, 'lang' => 'en' ) );
            return;
        }
        
    }

    
    public function viewAction()
    {
    	//1. Generate viewParams;
    	$id = $this->_request->getParam("id");
    	if (!$a = $this->m->getArticleData($id))
        {
            $this->renderError(null,t(504));
            return;
        }
        if ($a['article_language'] != Zend_Registry::get('viewLang'))
            $this->viewParams['errorMessage'] = t(505);

        //$this->view->article = $a;
        $this->viewParams['article'] = $a;
        
        //generate $paramsForWidgets
        $this->paramsForWidgets['articleId'] = $id; 
    }
    
	public function editAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
		if (!isset($sess->userId))
		{
		 	$this->renderError(null,t(726));
        	return;	
		}
       	if (strpos ($sess->userPermissions, 'update article') === false)
	    {
	    	$this->viewParams['errorMessage'] = t(68);
    	 	$this->renderError(null,t(504));
            return;
	    }
		
        $this->viewParams['form'] = new Form_Article();
//        $this->viewParams['form']->cluBuild(array ('action' => 'edit','view' => $this->view));
        
        $actionUrl = $this->view->hvnUrl(array('module' => 'article', 'action'=>'edit'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'edit', 'action_url' => $actionUrl, 
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        
    	$id = $this->_request->getParam("id");
    	if (!$a = $this->m->findByPrimary($id))
        {                
			$this->renderError(null,t(504));
			return;	                                                                                                                                                                   
        }
        //everything's fine. Continue editing
        //populate the data with 
		if (!$this->_request->isPost())
            $this->viewParams['form']->populate($a->toArray());
		
        else if ($this->viewParams['form']->isValid($_POST))
        {	
            if ($this->m->saveRaw($a, $this->viewParams['form']->getValues(), $id, false))
            {
                $this->viewParams['operation'] = t(506);
                //$this->renderToHolder('common/success.phtml');
                return;
            }
            else 
                $this->viewParams['errorMessage'] = t(507);
        }
        else 
        	$this->viewParams['errorMessage'] = t(71);
        $this->viewParams['id'] = $id;
	}
    
    public function deleteAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'delete article') === false)
	    {
	    	$this->viewParams['errorMessage'] = t(68);
    	 	$this->renderError(null,t(504));
            return;
	    }
	    
    	if (!$id = $this->_request->getParam('id'))
    	{
    		$this->renderError(null,t(508));
			return;
        }
        
        if ($this->m->deleteByPrimary(array($id)))
        {
            $this->viewParams['operation'] = t(509);
            //$this->renderToHolder('common/success.phtml');
        }
		else
		{   
            $this->renderError(null,t(510));
			return;
		}   
    }

    public function searchAction()
    {	
    	$data = $this->_request->getParams();
      	$this->viewParams['form'] = new Form_Search();
//      	$this->viewParams['form']->cluBuild(array ('view' => $this->view));
      	
      	$actionUrl = $this->view->hvnUrl(array('module' => 'article', 'action'=>'search'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'search', 'action_url' => $actionUrl));
        
		if($this->_request->isPost() && $this->viewParams['form']->isValid($_POST))
		{
	    	if($paginator = $this->m->search($data))
    		{
    			$paginator = $this->generatePaginator($paginator, 1, $data['articles_per_page'], 3, 'Jumping');
                $this->viewParams['form']->populate($data);  
    			
    			//cache in $_SESSION
               	$sess = new Zend_Session_Namespace(CLU_NS);
               	$ses->searchParams->article = $data;
        	}
		}
        else if(!empty($data['page']) && $data['page'] != null){
			$sess = new Zend_Session_Namespace(CLU_NS);
			if(isset($sess->searchParams->article))
        		$dataSess = $sess->searchParams->article;
			
        	if(isset($dataSess))
           	{
               $select = $this->m->search($dataSess);
               $paginator = $this->generatePaginator($select, $this->_getParam('page'), $dataSess['articles_per_page'], 3, 'Jumping');
               //populate form
               $this->viewParams['form']->populate($dataSess);
           	}
        }
        
        if(isset($paginator))
       	{      
           	//find translated languages list
        	$mTranslation = new article_Model_Translation();
            $translated = array();
            foreach ($paginator as $a)
            {
            	$res = $mTranslation->findTranslatedLanguagesList($a['article_id']);
            	$t = '';
            	foreach ($res as $translation)
                	$t = $translation['language'] . ", " . $t; 
                $translated[$a['article_id']] = $t;
            }
            $this->viewParams['translated'] = $translated;
                
            $this->viewParams['paginator'] = $paginator;
    		$this->viewParams['articleList'] = $paginator->getCurrentItems();//list of found articles
            //$this->renderToHolder('index/list.phtml',false, null, 4,2); 
       	}
       	
        //$this->renderToHolder('index/search.phtml',false, null, 4,1); //search box 
    }
    
    public function bulkAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'administer user') === false)
	    {
    	 	$this->renderError(null,t(68));
            return;
	    }
	    
        $ids = $this->_request->getParam('articles');
        if (count($ids) > 0)
        {
        	$action = $this->_request->getParam('bulkaction');
            if ($action === 'delete')
            {
                if ($this->m->deleteByPrimary($ids))
                {
                    $this->viewParams['operation'] = t(509);
        		    //$this->renderToHolder('common/success.phtml');
					return;
                }
            }
            else if ($action === 'status')
            {
            	$data = array();
            	$data['status'] = $this->_request->getParam('changestatus');
            	$data['statuschange_reason'] = $this->_request->getParam('reason');
				if ($this->m->bulkUpdateStatus($ids, $data))
				{
				    $this->viewParams['operation'] = t(72);
				    //$this->renderToHolder('common/success.phtml');
				    return;        
				}
            }
        }
        $this->renderError(null,t(73));
		return;
        //$this->renderToHolder('common/error.phtml');  
    }
        
    public function translateAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'translate article') === false)
	    {
    	 	$this->renderError(null,t(68));
            return;
	    }
	    
    	$id = $this->_request->getParam("id");
    	if (!$a = $this->m->findByPrimary($id))
        {                
            $this->renderError(null,t(504));
			return;
        }
        //get language
        
        $to = $this->_request->getParam('tolang');
        $this->viewParams['id'] = $id;
        $this->viewParams['a'] = $a;
        $this->viewParams['tolang'] = $to;
        if(!$to)
        {
        	$this->presenceIdentifier = 2;
            //$this->renderToHolder('index/chooselanguage.phtml');
        	return;
        }
        else 
        {
            $this->viewParams['form'] = new article_Form_Translation();
//            $this->viewParams['form']->cluBuild(array ('action' => 'translate','view' => $this->view));
            
            $actionUrl = $this->view->hvnUrl(array('module' => 'article', 'action'=>'translate'), 'nocontroller');
        	$this->viewParams['form']->cluBuild(array('action' => 'translate', 'action_url' => $actionUrl, 
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        
        	$mTranslation = new article_Model_Translation();
    		if(!$t = $mTranslation->findByPrimary(array('id'=>$id,'language'=>$to)))
    		{
                $this->viewParams['errorMessage'] = t(74);
                $this->viewParams['act'] = 'new';
    		}
            else 
            {
                //article has been translated. Populate if first time (GET mode)
                if (!$this->_request->isPost())
                	$this->viewParams['form']->populate($t->toArray());
                $this->viewParams['act'] = 'update';
            }
            
          	if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST) )
    	    {
    	        $act = $this->viewParams['act'];//$this->_request->getParam('act');
    	        if ($act === 'new')
    	        {
    	            if ($mTranslation->insertRaw($this->_request->getParams()))
    	            {
        	            $this->viewParams['action'] = t(75);
        	            $this->viewParams['successMessage'] = t(106);
        	            //$this->renderToHolder("common/success.phtml");
        	            return;
                    }
                    else 
                    {
                    	$this->renderError(null,t(74));
                    	$this->viewParams['errorMessage'] = t(519);
						return;
                    }
    	        }
    	        else if ($act === 'update')
    	        {
    	        	if ($mTranslation->saveRaw($t, $this->_request->getParams(), $id, $to, false))
    	        	{    	        	
        	            $this->viewParams['action'] = t(76);
        	            $this->viewParams['successMessage'] = t(106);
        	            //$this->renderToHolder("common/success.phtml");
        	            return;
    	        	}
    	        }
    	     } 
        }
        //$this->renderToHolder('index/translate.phtml');   
    }

    public function successAction()
    {
         $this->viewParams['articleId'] =  $this->_request->getParam("lastInsertId");
         //$this->renderToHolder('index/postSuccess.phtml');  
    }
}
?>
